/**
 * 对象上传 API
 * @param {express request} req
 * @return {Promise} 上传任务的 Promise 对象
 */
// 获取基础配置
const config = require('../config')

const multiparty = require('multiparty')
const readChunk = require('read-chunk')
const shortid = require('shortid')
const fs = require('fs')
const fileType = require('file-type')
const CosSdk = require('../cos-nodejs-sdk-v5-self')

module.exports = function(req) {
  // 初始化 sdk
  const cos = new CosSdk({
    SecretId: config.SecretId,
    SecretKey: config.SecretKey,
    ServiceDomain: `http://${config.cos.fileBucket}-${config.AppId}.cos.${config.cos.region}.myqcloud.com/`, //bug add
    // FileParallelLimit: 3,
    // ChunkParallelLimit: 3,
    // ChunkSize: 1024 * 1024,
    // ProgressInterval: 1000,
    // Proxy: '',
  })

  const maxSize = config.cos.maxSize ? config.cos.maxSize : 10
  const fieldName = config.cos.fieldName ? config.cos.fieldName : 'file'

  // 初始化 multiparty
  const form = new multiparty.Form({
    encoding: 'utf8',
    maxFilesSize: maxSize * 1024 * 1024,
    autoFiles: true,
    uploadDir: '/tmp'
  })

  return new Promise((resolve, reject) => {
    // 从 req 读取文件
    form.parse(req, (err, fields = {}, files = {}) => {
      err ? reject(err) : resolve({ fields, files })
    })
  }).then(({ files }) => {
    if (!(fieldName in files)) {
      throw new Error('%s: 请求中没有名称为 %s 的field，请检查请求或 SDK 初始化配置')
    }

    const imageFile = files[fieldName][0]

    // 判断文件类型
    const buffer = readChunk.sync(imageFile.path, 0, 262)
    const resultType = fileType(buffer)
    //支持的文件格式
    // 'image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/flif', 'image/x-canon-cr2', 'image/tiff', 'image/bmp', 'image/vnd.ms-photo', 'image/vnd.adobe.photoshop', 'image/bpg', 'image/x-icon',
    //   'video/mp4', 'video/x-m4v', 'video/x-matroska', 'video/webm', 'video/quicktime', 'video/x-msvideo', 'video/x-flv', 'video/x-ms-wmv', 'video/mpeg', 'video/mp2t',
    //   'audio/midi', 'audio/mpeg', 'audio/m4a', 'audio/opus', 'audio/ogg', 'audio/x-flac', 'audio/x-wav', 'audio/amr',
    //   'font/woff', 'font/woff2', 'font/ttf', 'font/otf',
    //   'application/postscript', 'application/x-xz', 'application/x-sqlite3', 'application/x-nintendo-nes-rom', 'application/x-google-chrome-extension', 'application/vnd.ms-cab-compressed', 'application/x-deb', 'application/x-unix-archive', 'application/x-rpm', 'application/x-compress', 'application/x-lzip', 'application/x-msi', 'application/mxf', 'application/x-blender', 'application/epub+zip', 'application/x-xpinstall', 'application/zip', 'application/x-tar', 'application/x-rar-compressed', 'application/gzip', 'application/x-bzip2', 'application/x-7z-compressed', 'application/x-apple-diskimage', 'application/pdf', 'application/x-msdownload', 'application/x-shockwave-flash', 'application/rtf', 'application/wasm', 'application/octet-stream'
    var filetype = ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/flif', 'image/x-canon-cr2', 'image/tiff', 'image/bmp', 'image/vnd.ms-photo', 'image/vnd.adobe.photoshop', 'image/bpg', 'image/x-icon',
      'video/mp4', 'video/x-m4v', 'video/x-matroska', 'video/webm', 'video/quicktime', 'video/x-msvideo', 'video/x-flv', 'video/x-ms-wmv', 'video/mpeg', 'video/mp2t',
      'audio/midi', 'audio/mpeg', 'audio/m4a', 'audio/opus', 'audio/ogg', 'audio/x-flac', 'audio/x-wav', 'audio/amr']
    if (!resultType || !filetype.includes(resultType.mime)) {
      throw new Error('%s: 不支持上传类型为 %s 的文件')
    }

    // 生成上传传参数
    const srcpath = imageFile.path
    const imgKey = `${Date.now()}-${shortid.generate()}.${resultType.ext}`

    var tmpFolder=''
    if (resultType.mime.includes('image')){
      tmpFolder = '/image'
    } else if (resultType.mime.includes('video')) {
      tmpFolder = '/video'
    } else if (resultType.mime.includes('audio')) {
      tmpFolder = '/audio'
    } else {
      tmpFolder = '/others'
    }

    const uploadFolder = config.cos.uploadFolder ? config.cos.uploadFolder + tmpFolder + '/' : ''
    const params = {
      AppId: config.AppId,
      Bucket: config.cos.fileBucket,
      Region: config.cos.region,
      Key: `${uploadFolder}${imgKey}`,
      Body: fs.createReadStream(srcpath),
      ContentLength: imageFile.size
    }
//不检查权限问题，直接上传
    // return new Promise((resolve, reject) => {
    //   // 检查 bucket 是否存在
    //   cos.headBucket(params, (err, data) => {
    //     if (err) {
    //       reject(err)
    //       // remove uploaded file
    //       fs.unlink(srcpath)
    //     }

    //     // 不存在则创建 bucket
    //     if (!data.BucketExist) {
    //       cos.putBucket({
    //         AppId: config.AppId,
    //         Bucket: config.cos.fileBucket,
    //         Region: config.cos.region,
    //         ACL: 'public-read'
    //       }, function (err, data) {
    //         if (err) {
    //           reject(err)
    //           // remove uploaded file
    //           fs.unlink(srcpath)
    //         } else {
    //           resolve()
    //         }
    //       })
    //     } else {
    //       resolve()
    //     }
    //   })
    // }).then(() => {
      return new Promise((resolve, reject) => {
        // 上传图片
        cos.putObject(params, (err, data) => {
          if (err) {
            reject(err)
            // remove uploaded file
            fs.unlink(srcpath)
          }

          resolve({
            imgUrl: `${cos.options.ServiceDomain + uploadFolder+imgKey}`,
            size: imageFile.size,
            mimeType: resultType.mime,
            name: imgKey
          })

          // remove uploaded file
          fs.unlink(srcpath)
        })
      })
    //})
  }).catch(e => {
    if (e.statusCode === 413) {
      throw new Error('%s: %o'+e)
    } else {
      throw e
    }
  })
}